package servlet;


import Dao.UserDao;
import com.google.gson.Gson;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


class Result{
    private String result;
    Result(String str){
        result=str;
    }
}

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        Map map = new HashMap<>();

        PrintWriter writer = response.getWriter();
        Gson gson=new Gson();
        //获得数据
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");

        //判断登录账号与密码
        if (userName != null && password != null) {
            User u=new User(userName,password);
            UserDao userDao=new UserDao();
            String result=userDao.checkLogin(u);
            if(!result.equals("")){
                //1. 保存
                //request.getSession().setAttribute("user",u);
                //2. 跳转
                //request.getRequestDispatcher("listStudents4.jsp").forward(request,response);
                String json=gson.toJson(new Result("ok"));
                writer.write(json);
            }else{
//                map.put("result","false");
//                map.put("msg","登陆失败");
               // writer.write("<script>alert('用户未登录');location.href='index.html'</script>");
                String json=gson.toJson(new Result("false"));
                writer.write(json);
            }
        }
    }
}
